#include"mystdio.h"
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MODE 0666
MyFile* CreateFile(int fd,int flag)
{
	MyFile* file = (MyFile*)malloc(sizeof(MyFile));
	if (file ==NULL)
	{
		perror("CreateFile malloc failed!");
		exit(2);
	}
	file->fileno = fd;
	file->flag = flag;
	file->bufferlen = 0;
	file->flush_method = LINE_FLUSH;
	memset(file->outbuffer,0,sizeof(file->outbuffer));
	return file;
}
MyFile* MyFopen(const char* path,const char*mode)
{
	int flag = 0;
	int fd = -1;
	// 1. 先判断是什么权限
	if(strcmp(mode,"w") == 0)
	{
		flag = O_CREAT | O_TRUNC | O_WRONLY;
		fd = open(path,flag,MODE);
	}
	else if (strcmp(mode,"a") == 0)
	{
		flag = O_CREAT | O_APPEND | O_WRONLY;
		fd = open(path,flag,MODE);
	}
	else if(strcmp(mode,"r")==0)
	{

		flag = O_RDONLY;
		fd = open(path,flag);
	}
	if (fd < 0)
	{
		perror("MyFopen failed!");
		exit(1);
	}
	return CreateFile(fd,flag);
}	


void MyFclose(MyFile* file)
{
	if (file->fileno < 0) return ;
	Myfflush(file);
	close(file->fileno);
	file = NULL;

}

void Myfflush(MyFile* file)
{
	//  把用户的缓冲区拷贝到系统中
	int n = write(file->fileno,file->outbuffer,file->bufferlen);
	// 把系统的缓冲区拷贝到磁盘外设上
	fsync(file->fileno);
	file->bufferlen = 0;

}

int MyWrite(MyFile* file,void* str,int len)
{
	// 1. 把文件里面的缓冲区的内容 拷贝到 str
	memcpy(file->outbuffer+file->bufferlen,str,len);
	file->bufferlen += len;
	// 2. 判断刷新条件
	if ((file->flush_method & LINE_FLUSH) && file->outbuffer[file->bufferlen-1] == '\n')
	{
		Myfflush(file);
	}
	return 0;
}
